//
//  LoginViewController.m
//  YiLiao
//
//  Created by mac on 16/7/1.
//  Copyright © 2016年 Noah. All rights reserved.
//

#import "LoginViewController.h"
#import "ReViewController.h"
#import "TabBar.h"
#import <AFNetworking.h>
#import "Util.h"

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userTF;
@property (weak, nonatomic) IBOutlet UITextField *passTF;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"登录";
 
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSUserDefaults *usre=[NSUserDefaults standardUserDefaults];
    NSString *nameStr=[usre objectForKey:@"name"];
    NSString *pswStr=[usre objectForKey:@"psw"];
    if (nameStr ==nil) {
        NSLog(@"没有用户");
        
    }else{
        self.userTF.text=nameStr;
        self.passTF.text=pswStr;
    }
}


//登录界面
- (IBAction)loginBT:(id)sender {
    //判断用户密码是否为空，如果为空则返回输入框为第一响应者
    if (![self checkisNull]) {
        return;
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    if (manager) {
    NSDictionary *bodyDic = @{@"command":@"ST_L",@"name":[NSString stringWithFormat:@"%@",self.userTF.text],@"psw":[NSString stringWithFormat:@"%@",self.passTF.text]};
        [manager POST:@"http://localhost:8080/st/s" parameters:bodyDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *resultDic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if ([resultDic[@"result" ]isEqualToString:@"1"]) {
                //跳转页面
                TabBar *tab=[[TabBar alloc]init];
                [UIApplication sharedApplication].delegate.window.rootViewController = tab;
                
                //保存accesstoken
                [self saveAccessToken:resultDic];
            }
//            else{
//                [Util showAlertWithMessager:resultDic[@"error"] confirmBlock:^{
//                    [_passTF becomeFirstResponder];
//                }];
//            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            [Util showAlertWithMessager:@"请求数据失败,请稍后重试" confirmBlock:nil];
            
        } ];
    }
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromSet:[NSSet setWithObjects:@"text/html", nil]];
//    NSDictionary *bodyDic = @{@"command":@"ST_L",@"name":[NSString stringWithFormat:@"%@",self.userTF.text],@"psw":[NSString stringWithFormat:@"%@",self.passTF.text]};
//   [manager POST:@"http://localhost:8080/st/s" parameters:bodyDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary *info = (NSDictionary *)responseObject;
//        NSUserDefaults *userF = [NSUserDefaults standardUserDefaults];
//        NSString *accessT = [info objectForKey:@"access_token"];
//        [userF setObject:accessT forKey:@"access_token"];
//        if ([[info objectForKey:@"result"] isEqualToString:@"1"]) {
//            
//            
//            //跳转页面
//            TabBar *tab=[[TabBar alloc]init];
//            [UIApplication sharedApplication].delegate.window.rootViewController = tab;
//            
//            //保存accesstoken
//            [self saveAccessToken:info];
//            
//        }
//        else
//        {
//            NSLog(@"用户不存在，请注册");
//        }
    
        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"------%@",error);
//    }];
//    
   
    

    
    
}
//登录时间
-(void)saveAccessToken:(NSDictionary *)dic
{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *access=[dic objectForKey:@"access_token"];
    double time=[dic[@"time"]doubleValue];
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:time];
    [user setObject:date forKey:@"lose_time"];
    [user setObject:access forKey:@"access_token"];
    [user synchronize];
}

//判断用户密码是否为空，如果为空则返回输入框为第一响应者
-(BOOL)checkisNull{
    if ([_userTF.text isEqualToString:@""]) {
        [Util showAlertWithMessager: @"用户名不能为空!" confirmBlock:^{
            [_userTF becomeFirstResponder];
        }];
        return NO;
    }
    if ([_passTF.text isEqualToString:@""]) {
        [Util showAlertWithMessager: @"密码不能为空!" confirmBlock:^{
            [_passTF becomeFirstResponder];
        }];
        return NO;
    }
    return YES;
}

//注册
- (IBAction)reBut:(id)sender {
    ReViewController *reVC=[[ReViewController alloc]init];
    [self presentViewController:reVC animated:YES completion:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
